package com.gams.websocket.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gams.config.ConfigConstant;
import com.gams.device.led.Protocol;
import com.gams.device.print_jna.PrintCP;
import com.gams.device.voice.Jacob;
import com.gams.websocket.server.WebSocketServerHandler;
import lombok.extern.log4j.Log4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;

@Component
@Log4j
public class WebsocketClient implements InitializingBean
{
    public static WebSocketClient client;

    public static Boolean isRun = false;

    @Autowired
    private WebSocketServerHandler clientHandler;

    @Override
    public void afterPropertiesSet()
    {
        connect();
    }

    public void reConnect()
    {
        connect();
    }

    private void connect()
    {
        new Thread(() ->
        {
            try
            {
                client = new WebSocketClient(new URI("ws://" + ConfigConstant.ip + ":" + ConfigConstant.port + "/gams-api/ws"), new Draft_6455())
                {
                    @Override
                    public void onOpen(ServerHandshake serverHandshake)
                    {
                        log.info("握手成功");
                        isRun = true;
                    }

                    @Override
                    public void onMessage(String msg)
                    {
                        try
                        {
                            handleMsg(msg);
                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onClose(int i, String s, boolean b)
                    {
                        log.info("链接已关闭");
                        isRun = false;
                    }

                    @Override
                    public void onError(Exception e)
                    {
                        e.printStackTrace();
                        log.info("发生错误已关闭");
                    }
                };
            } catch (URISyntaxException ex)
            {
                ex.printStackTrace();
            }

            client.connect();
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN))
            {
                try
                {
                    Thread.sleep(100);
                } catch (InterruptedException exception)
                {
                    exception.printStackTrace();
                }
            }
            log.info("连接成功");
            client.send("{\"d\":\"" + ConfigConstant.deviceId + "\",\"c\":\"1\"}");
        }).start();
    }


    public void handleMsg(String msg)
    {
        log.debug("msg = " + msg);

        if (!msg.startsWith("{") || !msg.endsWith("}"))
        {
            log.info("消息不完整:" + msg);
            return;
        }

        JSONObject object = JSONObject.parseObject(msg);
        String command = object.getString("c");
        String deviceId = object.getString("d");
        String queueName = object.getString("b");
        String count = object.getString("count");
        String userName = object.getString("userName");
        String number = object.getString("number");
        String cardid = object.getString("cardid");
        String projectName = object.getString("projectName");
        String tips = object.getString("tips");
        String qrcodeUrl = object.getString("qrcodeUrl");
//        if (!"S000001".equals(deviceId)) {
//            log.info("未知来源消息");
//            return;
//        }

        switch (command)
        {
            //心跳
            case "2":
                break;
            //打印
            case "3":
                //T532
//                PrintUtil.print(projectName, qrcodeUrl, cardid, queueName, number, count, tips);
                //美松M80I
                /**
                 *    String qrcodeUrl = "http://192.168.16.219:8083/ruoyi-socket/swagger-ui/index.html";
                 *         String title = "深圳宝安港务中心欢迎您！";
                 *         String userName = "胡*宏";
                 *         String idcard = "430922********423X";
                 *         String bussinessName = "业务办理";
                 *         String queueNo = "A00001";
                 *         String text = "取号后请在大厅等候区域休息等候，因大厅实行无语音叫号，请注意显示屏提示，过号请重新取号，谢谢！";
                 */
//                int i = PrintJna.printNumber(projectName, qrcodeUrl, userName, cardid, queueName, number, tips);

                int i = PrintCP.printNumber(projectName, qrcodeUrl, userName, cardid, queueName, number, tips);
                //发送打印机状态
                clientHandler.send3(i);
                break;
            //LED
            case "4":
                JSONArray text = object.getJSONArray("data");
                Protocol.call(text);
                break;

            case "8":
                String data = object.getString("data");
                Jacob.textToSpeech(data);
        }
    }
}
